from datetime import datetime
import json
from flask_sqlalchemy import SQLAlchemy
from passlib.hash import bcrypt
from flask import current_app, jsonify
import requests
from sqlalchemy.orm import Session

from admin_models.model_public import BackgroundImage, BottomInfo, Nav, policyFiles

from utils.extensions import db
from utils.tool import setResponseData


def getNavList(status=None):
    try:
        nav_items = Nav.query.order_by(Nav.sort).all()

        response_data = [item.getList(status) for item in nav_items if item.getList(status) is not None]

        return setResponseData('10000000', 'success', response_data)

    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")

# 政策文件
def getPolicyFilesList(area=None, major1=None, major2=None, keyword=None, page=1, pageSize=10):
    try:
        session = db.session
        list = policyFiles.getList(session, area, major1, major2, keyword, page, pageSize)

        return setResponseData('10000000', 'success', list)

    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")


# 获取底部信息
def getBottomInfo(id):
    try:
        session = db.session
        bottom_info = BottomInfo.get_by_id(id, session)
        
        if bottom_info:
            return setResponseData('10000000', 'success', bottom_info.to_dict())
        else:
            return setResponseData('00000000', 'fail', "未找到底部信息")

    except Exception as e:
        current_app.logger.error(f"获取底部信息时发生错误：{e}")
        return setResponseData('00000000', 'fail', "获取底部信息失败")

    finally:
        db.session.close()


def getLocation():
    try:
        
        url = "https://api.map.baidu.com/location/ip"
        params = {
            "ak": "oIvGNTtVC8ekwDXmze21Q1BQXEwcGXtt"
        }
        
        response = requests.get(url, params=params)
        data = response.json()
        return setResponseData('10000000', 'success', data['content']['address_detail']['province'])
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    

def getActiveBackgroundImages():
    try:
        session = db.session
        active_images = BackgroundImage.get_active_images(session)
        
        if active_images:
            # 返回所有活跃的背景图片
            images_list = [image.to_dict() for image in active_images]
            return setResponseData('10000000', 'success', images_list)
        else:
            return setResponseData('00000000', 'fail', "未找到活动背景图片")

    except Exception as e:
        current_app.logger.error(f"获取活动背景图片时发生错误：{e}")
        return setResponseData('00000000', 'fail', "获取活动背景图片失败")

    finally:
        db.session.close()